GJ.add('app/ms_v2/common/base_page.js', ['jquery', 'app/common/widget/widget.js'], function (require, exports) {
    'use strict';
    var $ = require('jquery');
    var Widget = require('app/common/widget/widget.js');

    exports.initWidgets = Widget.initWidgets;

    exports.initWidget = Widget.initWidget;

    exports.ajaxWidget = function (config) {
        var $el = $(config.$el);
        var url = config.url;
        var render = Widget.template($(config.template).html());
        var dataType = config.dataType || 'json';
        var $target = config.$target || $el;

        $.get(url, function (data) {
            if (data) {
                if ($.isArray(data)) {
                    GJ.each(data, function (row) {
                        $target.append(render(row));
                    });
                } else {
                    $target.html(render(data));
                }
                if (config.showAfterDone) {
                    $el.show();
                }
            }
        }, dataType);
    };
    // 侧边浮动按钮
    exports.sideFloatWidget = Widget.define({
        events: {
            'click [data-role=backToTop]': 'backToTop',
            'click [data-role=small]': 'open',
            //'click [data-role=close]': 'onClose',
            //'click [data-role=wechatOpen]':'qrOpen',
            //'click [data-role=wechatClose]':'qrClose'
            'mouseenter [data-role=wechatOpen]':'qrOpen',//鼠标移入显示
            'mouseleave [data-role=wechatQrcode]':'qrClose'//鼠标移开隐藏
        },
        init: function (config) {
            var self = this;
            this.categoryId = config.categoryId;
            this.config = config;
            this.check();
            $(window)
                .on('resize', $.proxy(this.check, this))
                .on('scrollEvent', $.proxy(this.onScroll, this))
                .on('scroll',$.proxy(this.onScroll,this));

            setTimeout(function() {
                config.$el.addClass('backtotop-huodong-active');
            }, 4000);

            if(this.categoryId){
                this.categoryIdKey = 'categoryId_' + this.categoryId;
                GJ.use('js/util/storage/storage2.js', function(Storage){
                    self.storage = new Storage('slideFloatWidget');
                    var val = self.storage.get(self.categoryIdKey);
                    if(val !== -1){
                        self.open();
                    }
                });
            }
            this.qrcode = this.config.$wechatQrcode;
            this.qrcode && this.qrcode.data('shown',false);
            this.qrcodeClose = this.config.$wechatClose;
            this.wechatOpen = this.config.$wechatOpen;
            this.wechatOpen && this.wechatOpen.show();
        },
        onClose: function(e){
            e.preventDefault();
            this.close();
            this.forbidShow();
        },
        forbidShow: function(){
            var date = new Date();
            var empires = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
            if(this.storage){
                var val = this.storage.get(this.categoryIdKey);
                if(val !== -1){
                    this.storage.set(this.categoryIdKey, -1, empires);
                }
            }
        },
        open: function() {
            this.config.$el.addClass('backtotop-active');
        },
        close: function() {
            this.config.$el.removeClass('backtotop-active');
            this.config.$el.removeClass('backtotop-huodong-active');
        },
        onScroll: function () {
            var $el = this.config.$backToTop;
            var height = this.config.showBtnHeight || 500;

            var top = document.documentElement.scrollTop || document.body.scrollTop;

            if (top > height && !$el.data('shown')) {
                $el.data('shown', true);
                $el.css('display', 'block');
            } else if (top < height && $el.data('shown')) {
                $el.data('shown', false);
                $el.hide();
            }
        },
        check: function () {
            if (GJ.getViewPort().width < 1124) {
                this.hide();
                return false;
            } else {
                this.show();
                return true;
            }
        },
        hide: function () {
            this.$el.hide();
        },
        show: function () {
            this.$el.show();
        },
        backToTop: function (e) {
            e.preventDefault();
            var handler = document.body.scrollTop ? document.body : document.documentElement;
            if (handler.scrollTop) {
                $(handler).animate({
                    scrollTop: 0
                }, 100);
            }
        },
        qrOpen:function(e){
            e.preventDefault();
            if(!this.qrcode.data('shown')){
                this.qrcode.show();
                this.qrcode.data('shown',true);
                //this.qrcodeClose.show(); //去掉关闭按钮
                this.wechatOpen.addClass('wechat-qr-hover');
                this.wechatOpen.removeClass('wechat-qr-none');
                this.wechatOpen.hide();
            }else{
                this.qrClose(e);
            }
        },
        qrClose:function(e){
            this.wechatOpen.show();
            e.preventDefault();
            this.qrcode.hide();
            this.qrcode.data('shown',false);
            //this.qrcodeClose.hide(); 去掉关闭按钮
            this.wechatOpen.removeClass('wechat-qr-hover');
            this.wechatOpen.addClass('wechat-qr-none');
        }
    });
    exports.sideFloatWechatWidget = Widget.define({
        events:{
            'click [data-role=wechatOpen]':'onOpen',
            'click [data-role=wechatClose]':'onClose'
        },
        init:function(config){

        },
        onOpen:function(){

        },
        onClose:function(){

        }
    });


    // 回到顶部（需要废除）
    exports.topScroller = function (config) {
        var $el = $(config.$el);

        if (GJ.getViewPort().width < 1024) {
            $el.hide();
            return;
        }
        var shown = false;
        var minHeight = 500;

        if (document.body.scrollTop > minHeight || document.documentElement.scrollTop > minHeight) {
            $el.show();
        }

        $el.click(function () {
            var handler = document.body.scrollTop ? document.body : document.documentElement;
            if (handler.scrollTop) {
                $(handler).animate({
                    scrollTop: 0
                }, 100);
            }

            return false;
        });
        $(window).on('scroll', function () {
            var top = document.documentElement.scrollTop || document.body.scrollTop;
            if (top > minHeight && !shown) {
                shown = true;
                $el.css('display', 'block');
            }

            if (!top && shown) {
                shown = false;
                $el.hide();
            }
        });
    };

    // 意见反馈
    exports.feedBack = function (config) {
        if (GJ.getViewPort().width >= 1024) {
            $(config.$el).show();
        }
    };

    exports.hoverWidget = function (config) {
        var $el = $(config.$el);
        var $panel = $el.find('.js-need-iframe-bg');
        var $iframeBG = null;

        if ($panel.size() && GJ.ua && GJ.ua.ie === 6) {
            $iframeBG = $('<iframe></iframe>');
            $iframeBG
                .attr({
                    border : 0,
                    frameSpacing : 0,
                    frameBorder : 0,
                    scrolling : 'no'
                })
                .addClass('iframe-bg');
            var parentPos = $panel.parent().css('position');
            var isAppendToParent = parentPos === 'relative' || parentPos === 'absolute';

            if (isAppendToParent) {
                $panel.parent().prepend($iframeBG);
            } else {
                $('body').prepend($iframeBG);
            }
        }

        $el
            .mouseenter(function () {
                if (config.$activeBlock) {
                    config.$activeBlock.addClass('active');
                } else {
                    $el.addClass('active');
                }

                if ($iframeBG) {
                    var pos = {};

                    if (isAppendToParent) {
                        pos = $panel.position();
                    } else {
                        pos = $panel.offset();
                    }

                    $iframeBG
                        .css({
                            left: pos.left,
                            top: pos.top,
                            width: $panel.outerWidth(true),
                            height: $panel.outerHeight(true)
                        })
                        .show();
                }
            })
            .mouseleave(function () {
                if (config.$activeBlock) {
                    config.$activeBlock.removeClass('active');
                } else {
                    $el.removeClass('active');
                }

                if ($iframeBG) {
                    $iframeBG.hide();
                }
            });
    };

    // 顶部导航
    exports.topNav = function (config) {
        var $el = $(config.$el);
        var $ul = $el.find('.js-list');
        var $btn = $el.find('.js-btn');

        var $headEl = $('#header');
        //顶部点击统计
        GJ.use('log_tracker', function () {
            $headEl.on('click', 'a', function() {
                GJ.LogTracker.trackEvent('/all@pos=top_guide@atype=click');
            });
        });

        $btn
            .mouseenter(function () {
                $el.addClass('active');
            })
            .one('mouseenter', function () {
                GJ.use('app/ms_v2/template/top_nav.js', function (content) {
                    $ul.html(content);
                    GJ.use('log_tracker', function () {
                        GJ.LogTracker.bindAllTrackEvent();
                    });
                });
            });

        $el.mouseleave(function () {
            $el.removeClass('active');
        });
    };

    // 初始化页面中的全部placeholder
    exports.initPlaceholders = function () {
        GJ.use(['jquery', 'js/util/jquery/plugin/placeholder/jquery.placeholder.js'], function ($) {
            $(function () {
                $('[placeholder]').each(function () {
                    $(this).placeholder();
                });
            });
        });
    };

    exports.initWebIM = function () {
        if(window.location.search.indexOf('disablewebim=1') > -1) {
            return false;
        }
        GJ.use('tool/webim/js/webim.js');
    };

    exports.initLogTracker = function (config) {
        config = config || window.PAGE_CONFIG.logTracker || {};
        GJ.use('log_tracker', function () {
            if (config.gjch) {
                GJ.LogTracker.gjch = config.gjch;
            }
            if (config.gjchver) {
                GJ.LogTracker.gjchver = config.gjchver;
            }
            if (config.reqid) {
                GJ.LogTracker.reqid = config.reqid;
            }

            if (config.gjchNew) {
                GJ.LogTracker.gjchNew = config.gjchNew;
            }

            if (config.server) {
                GJ.LogTracker.server = config.server;
            }

            GJ.LogTracker.bindSpeedEvent();

            exports.initEventLog(config);

            exports.sendPageViewLog(config);
            exports.sendPageSpeedLog(config);
        });
    };

    exports.initEventLog = function (config) {
        config = config || window.PAGE_CONFIG.logTracker || {};

        GJ.use('log_tracker', function () {
            if (config.gjch) {
                GJ.LogTracker.gjch = config.gjch;
            }
            GJ.LogTracker.bindAllTrackEvent();
        });
    };

    exports.sendPageViewLog = function (config) {
        config = config || window.PAGE_CONFIG.logTracker || {};

        GJ.use('log_tracker', function () {
            GJ.LogTracker.trackPageView(config.gjch);
        });
    };

    exports.sendPageSpeedLog = function (config) {
        config = config || window.PAGE_CONFIG.logTracker || {};

        GJ.use('log_tracker', function () {
            GJ.LogTracker.trackSpeedEvent(config.gjch);
        });
    };

    exports.sendGooglePvLog = function (key) {
        key = key || 'UA-479320-1';
        GJ.use('js/app/common/google/google.js', function () {
            GJ.google.trackPageview(key);
        });
    };

    // 登录信息
    exports.userinfoWidget = Widget.define({
        init: function(config) {
            this.config = config;
            this.updateWidget();
        },
        updateWidget: function() {
            var config = this.config;
            var userinfo = GJ.getCookie('GanjiUserInfo');
            var t3       = GJ.getCookie('t3');
            try {
                userinfo = GJ.jsonDecode(userinfo) || {};
            } catch (ex) {
                userinfo = {};
            }
            var username = t3 ? userinfo.nickname : (GJ.jsonDecode(GJ.getCookie('GanjiUserInfo')) || {}).user_name;
            username = username || '';

            if (username) {
                GJ.use(['app/ms_v2/widget/userinfo.js'], function (userinfo) {
                    config.username = username;
                    userinfo(config);
                });
            }
        }
    });

    // 定向推广绑定事件
    exports.selfDirectionBind = function (config) {
        GJ.use('jquery', function ($) {
            if ($(config.$el).find('.js-lazy-load').size()) {
                GJ.use('js/util/lazyload/jquery.lazyload.1.7.js', function ($) {
                    $(config.$el).find('.js-lazy-load').lazyload();
                });
            }
        });

        GJ.use('js/app/self_direction/direction.js', function(){
            GJ.app.selfDirection.bind(config);
        });
    };

    // 渲染定向推广帖子
    exports.selfDirectionRender = function (config) {
        GJ.use('js/app/self_direction/direction.js', function(){
            GJ.app.selfDirection.render(config);
        });
    };

    // 判断页面是否来自seo
    exports.pageFromSeo = function () {

        var websites = [
            'http://www.baidu.com',
            'http://www.google.com',
            'http://www.so.com',
            'http://www.soso.com',
            'http://www.sogou.com'
        ];

        var referrer = document.referrer;

        for (var i = 0, length = websites.length; i < length; i++) {

            if (referrer.indexOf(websites[i]) > -1) {
                return true;
            }
        }
        return false;
    };

    exports.addCityDomainCookie = function (cityDomain) {
        var cookieName = 'citydomain';
        var prevCity = GJ.getCookie(cookieName);
        var cookieTime = 31536000; // 1 year

        if (cityDomain && cityDomain !== prevCity) {
            GJ.setCookie(cookieName, cityDomain, cookieTime);
            return;
        }

        GJ.use('js/app/data/city_domain.js', function (data){
            var cityData = {};
            var m = /^https?:\/\/(?:[^\.]+\.)?([^\.]+)\.(?:ganji.(?:com|cn))(?:\/([^$\/]+)(?:$|\/))?/.exec(window.location.href);

            GJ.each(data, function (v){
                cityData[v] = 1;
            });

            if (!m) {
                return;
            }
            if (m[1] && cityData[m[1]]) {
                cityDomain = m[1];
            } else if (m[2] && cityData[m[2]]) {
                cityDomain = m[2];
            }
            if (cityDomain && cityDomain !== prevCity) {
                GJ.setCookie(cookieName, cityDomain, cookieTime);
            }
        });
    };

    exports.initUUID = function () {
        GJ.use('js/util/uuid/uuid.js', function (UUID) {
            UUID();
        });
    };

    exports.checkCDN = function () {
        GJ.use('js/util/log_tracker/check_cdn.js', function (checkCDN) {
            checkCDN();
        });
    };

    exports.checkNP = function () {
        GJ.use('js/util/log_tracker/check_np.js', function (checkNP) {
            checkNP();
        });
    };

    exports.triggerScroll = function() {
        var timer = null;
        var $win = $(window);

        $win.on('scroll', function() {
            clearTimeout(timer);
            timer = setTimeout(function() {
                $win.trigger('scrollEvent');
            }, 30);
        });
    };

    exports.first = function () {
        exports.initUUID();
        exports.initPlaceholders();
        exports.initWidgets();
    };

    var defer = $.Deferred();

    exports.last = function (config) {
        exports.triggerScroll();
        // 判断是否为宽屏
        if (window.screen.width > 1280) {
            GJ.setCookie('lg', 1, 604800);
        } else {
            GJ.removeCookie('lg');
        }

        var isSSLPage = (window.location.protocol === 'https:');

        exports.initLogTracker();

        if (window.PAGE_CONFIG.GOOGLE_ANA_CODE) {
            exports.sendGooglePvLog(window.PAGE_CONFIG.GOOGLE_ANA_CODE);
        }

        if (!config || !config.disableWebim) {
            exports.initWebIM();
        }

        if (GJ.rand(1, 500) === 1 || window.location.href.indexOf('check_dnspod')) {
            GJ.use('js/util/log_tracker/check_dnspod.js', function (check) {
                check();
            });
        }
        if (!isSSLPage) {
            if (GJ.rand(1, 50) === 1 || window.location.href.indexOf('check_cdn') !== -1) {
                exports.checkCDN();
            }

            if (window.performance && (GJ.rand(1, 10) === 1 || window.location.href.indexOf('check_np') !== -1)) {
                exports.checkNP();
            }
        }

        defer.resolve();

        exports.selfDirectionRender();

        setTimeout(function() {
            var isTargetUser = false;
            if ( (GJ.ua.chrome > 20 || GJ.ua.ie > 8) && !isSSLPage) {
                if(GJ.rand(1, 50) === 10 && Object.keys && Array.prototype.forEach) {
                    isTargetUser = true;
                }
            }
            if(window.location.search.indexOf('istargetuser') !== -1) {
                isTargetUser = true;
            }
            if (isTargetUser && !GJ.config.debug) {
                setTimeout(function() {
                    GJ.use('js/util/md5/md5.js', function(MD5) {
                        var fileNames = [];
                        var url = 'http://tralog.ganji.com/sta/md5.gif?';
                        var fileNames = Object.keys(GJ.Module.cache).filter(function (fileName) {
                            return fileName.indexOf('guid_') === -1 &&
                                fileName.indexOf('http') === -1 &&
                                fileName.indexOf('.css') === -1 &&
                                GJ.Module.cache[fileName].factory;
                        });
                        var fileName = fileNames[GJ.rand(0, fileNames.length -1)];
                        var factory = GJ.Module.cache[fileName].factory;
                        var fileMD5 = '';

                        if (factory) {
                            fileMD5 = MD5(factory.toString().trim().replace(/^function\s*\((.*?)\)\s*{/, 'function($1){'));
                            url += 'file=' + fileName +'&md5=' + fileMD5 + '&dt=' + new Date().getTime();
                        }

                        var img = new Image();
                        img.src = url;
                    });
                }, 5000);
            }
        }, 3000);
    };
    exports.zzlast = function (config) {
        exports.triggerScroll();
        // 判断是否为宽屏
        if (window.screen.width > 1280) {
            GJ.setCookie('lg', 1, 604800);
        } else {
            GJ.removeCookie('lg');
        }

        var isSSLPage = (window.location.protocol === 'https:');

        if (GJ.rand(1, 500) === 1 || window.location.href.indexOf('check_dnspod')) {
            GJ.use('js/util/log_tracker/check_dnspod.js', function (check) {
                check();
            });
        }
        if (!isSSLPage) {
            if (GJ.rand(1, 50) === 1 || window.location.href.indexOf('check_cdn') !== -1) {
                exports.checkCDN();
            }

            if (window.performance && (GJ.rand(1, 10) === 1 || window.location.href.indexOf('check_np') !== -1)) {
                exports.checkNP();
            }
        }
        defer.resolve();
        // exports.selfDirectionRender();
        setTimeout(function() {
            var isTargetUser = false;
            if ( (GJ.ua.chrome > 20 || GJ.ua.ie > 8) && !isSSLPage) {
                if(GJ.rand(1, 50) === 10 && Object.keys && Array.prototype.forEach) {
                    isTargetUser = true;
                }
            }
            if(window.location.search.indexOf('istargetuser') !== -1) {
                isTargetUser = true;
            }
            if (isTargetUser && !GJ.config.debug) {
                setTimeout(function() {
                    GJ.use('js/util/md5/md5.js', function(MD5) {
                        var fileNames = [];
                        var url = 'http://tralog.ganji.com/sta/md5.gif?';
                        var fileNames = Object.keys(GJ.Module.cache).filter(function (fileName) {
                            return fileName.indexOf('guid_') === -1 &&
                                fileName.indexOf('http') === -1 &&
                                fileName.indexOf('.css') === -1 &&
                                GJ.Module.cache[fileName].factory;
                        });
                        var fileName = fileNames[GJ.rand(0, fileNames.length -1)];
                        var factory = GJ.Module.cache[fileName].factory;
                        var fileMD5 = '';

                        if (factory) {
                            fileMD5 = MD5(factory.toString().trim().replace(/^function\s*\((.*?)\)\s*{/, 'function($1){'));
                            url += 'file=' + fileName +'&md5=' + fileMD5 + '&dt=' + new Date().getTime();
                        }

                        var img = new Image();
                        img.src = url;
                    });
                }, 5000);
            }
        }, 3000);
    };
    exports.always = function (fn) {
        defer.always(fn);
    };
});